import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
//引入axios
import axios from 'axios'
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios
//设置请求的公共前缀
axios.defaults.baseURL="http://localhost:";
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'
/*import Mock from './mock'*/
//Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
  routes
})
/*axios前置拦截器（发送请求前  先执行者里面的代码）*/
axios.interceptors.request.use(config => {
    //携带token
    let token = localStorage.getItem("token");
    if (token) {
        //判断 如果token有值--》在头信息中添加token
        config.headers['token'] = token;
    }
    return config;
}, error => {
    Promise.reject(error);
});

//axios后置拦截器  在ajax请求后台数据返回前端规定展示效果之前执行
axios.interceptors.response.use(result => {
    let {success, msg} = result.data;
    if(!success && msg === "noLogin"){
        //清空本地存储
        localStorage.removeItem("token");
        localStorage.removeItem("loginUser");
        router.push({ path: '/login' });
    }
    //result就是后台返回的数据
    return result;
}, error => {
    Promise.reject(error);
});



//路由的拦截器
router.beforeEach((to, from, next) => {
    //如果你访问的目标资源是/login 或者/shopRegister 我就直接放行
    if(to.path=="/login"||to.path=="/shopRegister"){
        //放行让其执行目标资源
        next();
    }else{
        //如果是访问其他资源，我就要获取token是否有值
        var token = localStorage.getItem("token");
        //如果token有值，就直接放行
        if(token){
            next();
        }else{
            //那就直接跳转到登录界面
            next({path: '/login'});
        }
    }
})



//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

